package cn.hdu.liang.ch7;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Dictionary {
    public static void main(String[] args) {
        final String[] words = {"hypocalcemia", "prolixity", "assiduous", "indefatigable", "castellan"};
        final String[] definitions = {"低血钙症", "啰嗦", "刻苦的、勤勉的", "不知疲倦的", "城主"};
        final Map<String, String> dictionary = new HashMap<>();

        ReadWriteLock rwl = new ReentrantReadWriteLock(true);
        final Lock rlock = rwl.readLock();
        final Lock wlock = rwl.writeLock();

        Runnable writer = () -> {
            for(int i = 0; i < words.length; i++) {
                wlock.lock();
                try {
                    dictionary.put(words[i], definitions[i]);
                    System.out.println("写者存储 " + words[i]);
                } finally {
                    wlock.unlock();
                }
            }
        };
        ExecutorService es = Executors.newFixedThreadPool(1);
        es.submit(writer);

        Runnable reader = () -> {
            for(int i = 0; i < 10; i++) {
                rlock.lock();
                try {
                    int v = new Random().nextInt(words.length);
                    System.out.println("读者访问 " + words[v] + " : " + dictionary.get(words[v]));
                } finally {
                    rlock.unlock();
                }
            }
        };
        es = Executors.newFixedThreadPool(1);
        es.submit(reader);
    }
}
